﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace GWSoft.Framework.WebSite.Controllers
{
    /// <summary>
    /// 授权控制类
    /// </summary>
    [Route("[controller]")]
    public class AuthenticationController : Controller
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        public AuthenticationController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 配置
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 提交获取Token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post()
        {
            if (!Request.Headers["Authorization"].Any())
            {
                return BadRequest();
            }
            var authorizationHeader = Request.Headers["Authorization"].First();
            var key = authorizationHeader.Split(' ')[1];
            var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(key)).Split(':');
            var serverSecret = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:ServerSecret"]));
            if(credentials[0] == "username" && credentials[1] == "password")
            {
                var result = new
                {
                    token = GenerateToken(serverSecret)
                };

                return Ok(result);
            }

            return BadRequest();
        }

        private string GenerateToken(SecurityKey key)
        {
            var now = DateTime.UtcNow;
            var issuer = Configuration["JWT:Issuer"];
            var audience = Configuration["JWT:Audience"];
            var identity = new ClaimsIdentity();
            var signingCredential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var handler = new JwtSecurityTokenHandler();
            var token = handler.CreateJwtSecurityToken(issuer, audience, identity, now, now.Add(TimeSpan.FromDays(1)),
                now, signingCredential);
            var encodedJwt = handler.WriteToken(token);

            return encodedJwt;
        }
    }
}
